import Flutter
import UIKit

public class FlutterWorldCupPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
  private var eventSink: FlutterEventSink?
  private let countries = [
      "Russia 2018", "Brazil 2014", "South Africa 2010", "Germany 2006",
      "South Korea/Japan 2002", "France 1998", "USA 1994"
  ]
  private var index = 0
  private var timer: Timer?

  public static func register(with registrar: FlutterPluginRegistrar) {
    let eventChannel = FlutterEventChannel(name: "com.example.world_cup/countries", binaryMessenger: registrar.messenger())
    let instance = FlutterWorldCupPlugin()
    eventChannel.setStreamHandler(instance)
  }

  public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
    self.eventSink = events
    startSendingCountries()
    return nil
  }

  public func onCancel(withArguments arguments: Any?) -> FlutterError? {
    timer?.invalidate()
    timer = nil
    return nil
  }

  private func startSendingCountries() {
    index = 0
    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
      if self.index < self.countries.count {
        self.eventSink?(self.countries[self.index])
        self.index += 1
      } else {
        self.eventSink?(FlutterEndOfEventStream)
        self.timer?.invalidate()
      }
    }
  }
}
